package com.example.clxy.service.impl;

import com.example.clxy.dao.ScheduleStudentGxMapper;
import com.example.clxy.entity.ScheduleStudentGx;
import com.example.clxy.entity.ScheduleStudentGxKey;
import com.example.clxy.entity.dto.RegDto;
import com.example.clxy.result.PageResult;
import com.example.clxy.result.WebRestResult;
import com.example.clxy.result.business.PageResult.StudentScorePageResult;
import com.example.clxy.result.business.RegResult;
import com.example.clxy.result.business.StudentScoreResult;
import com.example.clxy.service.ScoreService;
import com.example.clxy.util.FileUtil;
import com.example.clxy.util.RespUtil;
import com.example.clxy.util.Tools;
import com.itextpdf.text.DocumentException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;


import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author weichong
 * date 2020-08-05
 * @Description:
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)

public class ScoreServiceImpl implements ScoreService {
    @Autowired
    private ScheduleStudentGxMapper scheduleStudentGxMapper;

    @Override
    public WebRestResult updateScore(String scheduleid, String studentid, Double yxscore, Double sykscore,
                                     Double sybgscore, String yxscorereason, String sykscorereason,
                                     String sybgscoreason, Double sygfxscore, Double sbwhscore, Double xczlscore) {
        if (Tools.isEmpty(scheduleid) || Tools.isEmpty(studentid)) {
            return RespUtil.failResp("排课id和学生id不能为空!");
        }

        ScheduleStudentGxKey scheduleStudentGxKey = new ScheduleStudentGxKey(scheduleid, studentid);
        ScheduleStudentGx studentGx = scheduleStudentGxMapper.selectByPrimaryKey(scheduleStudentGxKey);
        if (studentGx == null) {
            return RespUtil.failResp("该学生排课不存在");
        }
        if (checkScore(studentGx)) {
            return RespUtil.failResp("分数只能设置一次!");
        }

        if (Tools.isScore(yxscore) && Tools.isEmpty(studentGx.getYxscore())) {
            studentGx.setYxscore(yxscore);
            studentGx.setYxscorereason(yxscorereason);
        }
        if (Tools.isScore(sykscore) && Tools.isEmpty(studentGx.getSykscore())) {
            studentGx.setSykscore(sykscore);
            studentGx.setSykscorereason(sykscorereason);
        }
        if (Tools.isScore(sybgscore) && Tools.isEmpty(studentGx.getSybgscore())) {
            studentGx.setSybgscore(sybgscore);
            studentGx.setSybgscoreason(sybgscoreason);
        }
        if (Tools.isScore(sygfxscore) && Tools.isEmpty(studentGx.getSygfxscore())) {
            studentGx.setSygfxscore(sygfxscore);
        }
        if (Tools.isScore(sbwhscore) && Tools.isEmpty(studentGx.getSbwhscore())) {
            studentGx.setSbwhscore(sbwhscore);
        }
        if (Tools.isScore(xczlscore) && Tools.isEmpty(studentGx.getXczlscore())) {
            studentGx.setXczlscore(xczlscore);
        }

        if (scheduleStudentGxMapper.updateByPrimaryKeySelective(studentGx) == 1) {
            if (checkScore(studentGx)) {
                updatePsscoreFinalscore(scheduleid, studentid);
            }
            return RespUtil.successResp("修改成功");
        }
        return RespUtil.failResp("修改失败");
    }

    /**
     * 判断是否已经完成打分,完成打分返回true
     **/
    public boolean checkScore(ScheduleStudentGx studentGx) {
        if (Tools.notEmpty(studentGx.getYxscore())
                && Tools.notEmpty(studentGx.getSykscore())
                && Tools.notEmpty(studentGx.getSybgscore())
                && Tools.notEmpty(studentGx.getSygfxscore())
                && Tools.notEmpty(studentGx.getSbwhscore())
                && Tools.notEmpty(studentGx.getXczlscore())
        ) {
            return true;
        }
        return false;
    }

    /**
     * 平时成绩 = 预习报告成绩 * 系数 + 实验规范性得分 * 系数 + 设备维护得分 * 系数 + 现场整理得分 * 系数
     * 总成绩 = 实验卡成绩 * 系数 + 实验报告成绩 * 系数 + 平时成绩
     **/
    @Override
    public void updatePsscoreFinalscore(String scheduleid, String studentid) {
        ScheduleStudentGxKey scheduleStudentGxKey = new ScheduleStudentGxKey(scheduleid, studentid);
        ScheduleStudentGx scheduleStudentGx = scheduleStudentGxMapper.selectByPrimaryKey(scheduleStudentGxKey);
        //获取成绩规格化系数列表
        List<Double> scoreRatioList = scheduleStudentGxMapper.getSorceRatioLis();
        Double score = 0.0;
        if (scheduleStudentGx.getYxscore() != null) {
            score += scheduleStudentGx.getYxscore() * scoreRatioList.get(0);
            scheduleStudentGx.setYxscorereg(scheduleStudentGx.getYxscore() * scoreRatioList.get(0));
        }
        if (scheduleStudentGx.getSygfxscore() != null) {
            score += scheduleStudentGx.getSygfxscore() * scoreRatioList.get(1);
            scheduleStudentGx.setSygfxscorereg(scheduleStudentGx.getSygfxscore() * scoreRatioList.get(1));
        }
        if (scheduleStudentGx.getSbwhscore() != null) {
            score += scheduleStudentGx.getSbwhscore() * scoreRatioList.get(2);
            scheduleStudentGx.setSbwhscorereg(scheduleStudentGx.getSbwhscore() * scoreRatioList.get(2));
        }
        if (scheduleStudentGx.getXczlscore() != null) {
            score += scheduleStudentGx.getXczlscore() * scoreRatioList.get(3);
            scheduleStudentGx.setXczlscorereg(scheduleStudentGx.getXczlscore() * scoreRatioList.get(3));
        }
        scheduleStudentGx.setPsscore(score);
        if (scheduleStudentGx.getSykscore() != null) {
            score += scheduleStudentGx.getSykscore() * scoreRatioList.get(4);
            scheduleStudentGx.setSykscorereg(scheduleStudentGx.getSykscore() * scoreRatioList.get(4));
        }
        if (scheduleStudentGx.getSybgscore() != null) {
            score += scheduleStudentGx.getSybgscore() * scoreRatioList.get(5);
            scheduleStudentGx.setSybgscorereg(scheduleStudentGx.getSybgscore() * scoreRatioList.get(5));
        }
        int newscore = (int) (Math.round(score));
        scheduleStudentGx.setFinalscore(newscore);
        scheduleStudentGxMapper.updateByPrimaryKeySelective(scheduleStudentGx);
    }

    @Override
    public StudentScoreResult mergePdfFilesByStudent(String scheduleid, String studentid) throws IOException, DocumentException {
        StudentScoreResult result = new StudentScoreResult();
        ScheduleStudentGx scheduleStudentGx = new ScheduleStudentGx();
        scheduleStudentGx.setScheduleid(scheduleid);
        scheduleStudentGx.setStudentid(studentid);
        ScheduleStudentGx gx = scheduleStudentGxMapper.selectByPrimaryKey(scheduleStudentGx);
        String studentPath = scheduleStudentGxMapper.getStudentPath(scheduleid, studentid);
        String filepath = FileUtil.getAbsolutePath(studentPath);
        ArrayList<String> list = new ArrayList<>();
        File file = null;

        String yxreport = filepath + "yxreport.pdf";
        file = new File(yxreport);
        if (file.exists()) {
            list.add(yxreport);
        }

        String sycard = filepath + "sycard.pdf";
        file = new File(sycard);
        if (file.exists()) {
            list.add(sycard);
        }

        String syreport = filepath + "syreport.pdf";
        file = new File(syreport);
        if (file.exists()) {
            list.add(syreport);
        }
        String filename = studentPath.replace('\\', '-')+".pdf";
        String mergepdf = filepath + filename;
        file = new File(mergepdf);
        if (!file.exists()) {
            boolean b = file.createNewFile();
            if (!b) {
                result.setResult(WebRestResult.FAILURE);
                result.setMessage("合并pdf文件创建失败！");
                return result;
            }
        }
        FileUtil.mergePdfFiles(list, mergepdf);
        String finalpdfpath = FileUtil.FilePathUrl + studentPath.replace('\\', '/') + filename;
        gx.setFinalpdfpath(finalpdfpath);
        gx.setUpdatedTime(new Date());
        gx.setFlag("0");
        if (scheduleStudentGxMapper.updateByPrimaryKeySelective(gx) == 1) {
            result.setResult(WebRestResult.SUCCESS);
            result.setMessage("合并pdf成功！");
            result.setFinalpdfpath(finalpdfpath);
            result.setScheduleid(scheduleid);
            result.setStudentid(studentid);
        } else {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("合并pdf失败！");
            result.setScheduleid(scheduleid);
            result.setStudentid(studentid);
        }
        return result;
    }

    @Override
    public WebRestResult updateReg(String dictid,String regscore) {
        WebRestResult result = new WebRestResult();

        scheduleStudentGxMapper.updateReg(dictid,regscore);
        List<Double> scoreRatioList = scheduleStudentGxMapper.getSorceRatioLis();
        double sum = 0.0;
        for (int i = 0; i < scoreRatioList.size(); i++) {
            sum += scoreRatioList.get(i);
        }
        if (sum > 1.0) {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("修改后计算成绩规格化的系数总和大于1，修改失败！可先修改规格化系数总和小于1");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        result.setResult(WebRestResult.SUCCESS);
        result.setMessage("修改成功！");
        return result;
    }

    @Override
    public RegResult getRegList() {
        RegResult result = new RegResult();
        List<Double> sorceRatioLis = scheduleStudentGxMapper.getSorceRatioLis();
        if (sorceRatioLis.size() > 0) {
            result.setYxscorereg(sorceRatioLis.get(0));
            result.setSygfxscorereg(sorceRatioLis.get(1));
            result.setSbwhscorereg(sorceRatioLis.get(2));
            result.setXczlscorereg(sorceRatioLis.get(3));
            result.setSykscorereg(sorceRatioLis.get(4));
            result.setSybgscorereg(sorceRatioLis.get(5));
            result.setResult(WebRestResult.SUCCESS);
            result.setMessage("获取规格化成绩列表成功");
        }
        return result;
    }

    @Override
    public WebRestResult updateReg1(RegDto regDto) {
        WebRestResult result = new WebRestResult();
        String label1 = regDto.getLabel1();
        String label2 = regDto.getLabel2();
        String label3 = regDto.getLabel3();
        String label4 = regDto.getLabel4();
        String label5 = regDto.getLabel5();
        String label6 = regDto.getLabel6();
        scheduleStudentGxMapper.updateReg("1", label1);
        scheduleStudentGxMapper.updateReg("2", label2);
        scheduleStudentGxMapper.updateReg("3", label3);
        scheduleStudentGxMapper.updateReg("4", label4);
        scheduleStudentGxMapper.updateReg("5", label5);
        scheduleStudentGxMapper.updateReg("6", label6);
        result.setResult(WebRestResult.SUCCESS);
        result.setMessage("更新规格化系数成功！");
        return result;
    }

    @Override
    public PageResult<StudentScorePageResult> getStudentScoreBySchedule(String scheduleid, String wlclassid, String studentname, String wlclassname, int page, int pagesize) {

        PageResult<StudentScorePageResult> res = new PageResult<>();
        int begin = (page - 1) * pagesize;
        int end = pagesize;

        List<StudentScorePageResult> studentScoreList = scheduleStudentGxMapper.getStudentScoreBySchedule(scheduleid, wlclassid, studentname, wlclassname, begin, end, pagesize);
        if (studentScoreList.size() > 0) {
            res.setTotal(studentScoreList.get(0).getCnt());
            res.setPageCount(studentScoreList.get(0).getPage());
            res.setRows(studentScoreList);
            res.setResult(WebRestResult.SUCCESS);
            res.setMessage("查询学生实验信息成功");
        }
        return res;
    }

    @Override
    public PageResult<StudentScorePageResult> getStudentScoreByStudent(String studentid, String scheduleid, String semesterid, int page, int pagesize) {
        PageResult<StudentScorePageResult> res = new PageResult<>();
        int begin = (page - 1) * pagesize;
        int end = pagesize;

        List<StudentScorePageResult> studentScoreList = scheduleStudentGxMapper.getStudentScoreByStudent(studentid, scheduleid, semesterid, begin, end, pagesize);
        if (studentScoreList.size() > 0) {
            res.setTotal(studentScoreList.get(0).getCnt());
            res.setPageCount(studentScoreList.get(0).getPage());
            res.setRows(studentScoreList);
            res.setResult(WebRestResult.SUCCESS);
            res.setMessage("查询学生实验信息成功");
        }
        return res;

    }

}
